#include "Token.h"
#include "Error.h"
#include <string>
#include <cassert>
using namespace std;
Context* Context::instance = NULL;
string Context::nextLine()
{
	if (end)
	{
		(stdOut()) << endl;
		throw ErrorExit();
	}
	row++;
	assert(row >= 1);
	std::string s;
	while (row > source.size())
	{
		if (prompt)
			std::cout << ">>> ";
		getline(*is, s);
		s = " " + s;
		s = removeComment(s);
		source.push_back(s);
	}
	//else
	{
		s = source[row-1];
	}
	//std::clog << "LINE" << row << " READ." << std::endl;
	if (!(*is))
		end = true; // not exit instantly
	return s;
}
string Context::removeComment(const string& raw) const
{
	char quote = '#';
	int i;
	for (i = 0; i < raw.size(); i++)
	{
		if (raw[i] == '\'')
			if (quote == '#')
				quote = '\'';
			else if (quote == '\'')
				quote = '#';
			else // quote == '"'
				quote = '"'; // do nothing
		else if (raw[i] == '"')
			if (quote == '#')
				quote = '"';
			else if (quote == '"')
				quote = '#';
			else // quote == '\''
				quote = '\''; // do nothing
		else if (raw[i] == '#')
			if (quote == '#')
				break;
			else
				;
	}
	int LnCr = raw.find('\r');
	if (LnCr != string::npos)
	{
		assert(LnCr == raw.size() - 1);
		if (i == raw.size())
			i = LnCr;
	}
	return raw.substr(0, i);
}

